package com.example.controller;

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.vo.SysResult;
import com.example.vo.SysResultData;

@RestController
@RequestMapping(value="/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public SysResult listUser(){
		SysResult result;
		try {
			List<User> list = userService.listAllUser();
			result = SysResultData.ok(list);
		} catch (Exception e) {
			result = SysResult.build(SysResult.STATUS_SERVER_ERROR);
		}
		return result;
	}
	
	@RequestMapping(value="/{id}/", method=RequestMethod.GET)
	public SysResult getUser(@PathVariable Long id){
		SysResult result;
		try {
			User user = userService.getUser(id);
			result = SysResultData.ok(user);
		} catch (EmptyResultDataAccessException | EntityNotFoundException e) {
			result = SysResult.build(SysResult.STATUS_PARAMETER_ERROR, "用户不存在");
		} catch (Exception e) {
			e.printStackTrace();
			result = SysResult.build(SysResult.STATUS_SERVER_ERROR);
		}
		return result;
	}
	
	
	@RequestMapping(value="/", method=RequestMethod.PUT)
	public SysResult addUser(User user){
		SysResult result;
		try {
			if (userService.saveUser(user)) {
				result = SysResult.ok();
			} else {
				result = SysResult.build(SysResult.STATUS_PARAMETER_ERROR, "用户已存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = SysResult.build(SysResult.STATUS_SERVER_ERROR);
		}
		return result;
	}
	
	@RequestMapping(value="/{id}/", method=RequestMethod.DELETE)
	public SysResult delUser(@PathVariable Long id){
		SysResult result;
		try {
			userService.deleteUser(id);
			result = SysResult.ok();
		} catch (EmptyResultDataAccessException e) {
			result = SysResult.build(SysResult.STATUS_PARAMETER_ERROR, "用户不存在");
		} catch (Exception e) {
			e.printStackTrace();
			result = SysResult.build(SysResult.STATUS_SERVER_ERROR);
		}
		return result;
	}
	
	@RequestMapping(value="/{id}/", method=RequestMethod.POST)
	public SysResult updateUser(User user){
		SysResult result;
		try {
			if (userService.updateUser(user)) {
				result = SysResult.ok();
			} else {
				result = SysResult.build(SysResult.STATUS_PARAMETER_ERROR, "用户不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = SysResult.build(SysResult.STATUS_SERVER_ERROR);
		}
		return result;
	}
	
}
